using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace AppManagement.MainManagers
{
	#region using
	using DevComponents.DotNetBar;
	using AppManagement.Models;
	using AppManagement.Repositories;
	using AppManagement.Helpers;
	using AppManagement.UsersManager;
	using System.Data;
	using System.Drawing;
	using System.IO;
	#endregion

	public partial class FrmLapPHIEUYEUCAU : Office2007Form
	{
		public EventHandler Handler { get; set; }
		private DataTable DataSource;
		private int PHIEUYEUCAU_ID;
        private int CHINHANH_ID = -1;

		public FrmLapPHIEUYEUCAU(int phieuyeucau_id = -1)
		{
			InitializeComponent();
			PHIEUYEUCAU_ID = phieuyeucau_id;
            txtNGAYYEUCAU.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Now);
            CHINHANH_ID = GlobalVariables.g_CurrentUser.NHANVIEN_CHINHANH.CHI_NHANH_ID.Value;
            txtCHINHANH.Text = GlobalVariables.g_CurrentUser.NHANVIEN_CHINHANH.CHINHANH.TEN_CHI_NHANH;
		}

		private void FrmLapPHIEUYEUCAU_Load(object sender, EventArgs e)
		{
			InitGridView();
			InitHiddenFields();
			InitDataSource();
			if (PHIEUYEUCAU_ID != -1)
			{
				LoadPHIEUYEUCAU();
			}
		}

		private void InitGridView()
		{
			DataGridViewTextBoxColumn objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "ID Thiết bị",
				DataPropertyName = "THIET_BI_ID",
				Name = "THIET_BI_ID",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/3))
			};
			dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "Tên thiết bị",
				DataPropertyName = "TEN_THIET_BI",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/3))
			};
			dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "Số lượng",
				DataPropertyName = "SO_LUONG",
				Name = "SO_LUONG",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/3)) - 1
			};
			dtgvData.Columns.Add(objColumn);
		}

		public void InitHiddenFields()
		{
		}

		public void InitDataSource()
		{
			DataSource = new DataTable();
			DataSource.Columns.Add("THIET_BI_ID");
			DataSource.Columns.Add("TEN_THIET_BI");
			DataSource.Columns.Add("SO_LUONG");
			DataView objTimeSheetDV = new System.Data.DataView(DataSource);
			objTimeSheetDV.AllowNew = false;
			dtgvData.AutoGenerateColumns = false;
			dtgvData.DataSource = objTimeSheetDV;
			dtgvData.ClearSelection();
		}


		private void btnThem_Click(object sender, EventArgs e)
		{
			FrmCapNhatCHITIETPHIEUYEUCAU frm = new FrmCapNhatCHITIETPHIEUYEUCAU();
			frm.Handler += GetCHITIETPHIEUYEUCAU;
			frm.ShowDialog();
		}

		public void GetCHITIETPHIEUYEUCAU(object sender, EventArgs e)
		{
			var eventType = (TransferSimpleDataEvent)e;
			string[] comp = eventType.Data.Split(new char[] { '#' });
			var item = THIETBIRepository.SelectByID(int.Parse(comp[0]));
			if(item != null)
			{
				DataSource.Rows.Add(item.THIET_BI_ID, item.TEN_THIET_BI, comp[1]);
			}
		}


		private void btnXoa_Click(object sender, EventArgs e)
		{
			if (DataSource.Rows.Count > 0)
			{
				DataSource.Rows.RemoveAt(dtgvData.SelectedRows[0].Index);
			}
		}

		private bool ValidateInput(ref string errorText)
		{
			if (DataSource.Rows.Count == 0)
			{
				errorText = "Danh sách hiện thời không có gì!";
				return false;
			}
			return true;
		}

		private void btnCapNhat_Click(object sender, EventArgs e)
		{
			var errorText = "";
			bool success = false;
			if (!ValidateInput(ref errorText))
			{
				MessageBoxEx.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			if (ActionUpdate())
			{
				success = true;
			}
			if (success)
			{
				MessageBoxEx.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			else
			{
				MessageBoxEx.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void btnThoat_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private bool ActionUpdate()
		{
			try
			{
				DataContext.Instance.Connection.Open();
				using (var transaction = DataContext.Instance.Connection.BeginTransaction())
				{
					var phieuyeucau = new PHIEUYEUCAU
					{
						NHANVIEN_ID = GlobalVariables.g_CurrentUser.NGUOIDUNG_ID,
						NGAY_YEU_CAU = DateTime.Now,
                        CHINHANH_ID = this.CHINHANH_ID,
                        DANG_XU_LY = false,
                        DA_XU_LY = false
					};
					if (PHIEUYEUCAURepository.Insert(phieuyeucau))
					{
						for (int i = 0; i <= DataSource.Rows.Count - 1; i++)
						{
							var chitietphieuyeucau = new CHITIETPHIEUYEUCAU
							{
								PHIEUYEUCAU_ID = phieuyeucau.PHIEUYEUCAU_ID,
								THIET_BI_ID = int.Parse(DataSource.Rows[i]["THIET_BI_ID"].ToString()),
								SO_LUONG = int.Parse(DataSource.Rows[i]["SO_LUONG"].ToString()),
                                DA_XUAT = 0
							};
							if (!CHITIETPHIEUYEUCAURepository.Insert(chitietphieuyeucau))
							{
								DataContext.Instance.Connection.Close();
								return false;
							}
						}
						transaction.Commit();
					}
					else
					{
						DataContext.Instance.Connection.Close();
						return false;
					}
				}
				DataContext.Instance.Connection.Close();
				return true;
			}
			catch
			{
				DataContext.Instance.Connection.Close();
				return false;
			}
		}

		private void LoadPHIEUYEUCAU()
		{
			var phieuyeucau = PHIEUYEUCAURepository.SelectByID(PHIEUYEUCAU_ID);
			if (phieuyeucau != null)
			{
				txtPHIEUYEUCAU_ID.Text = PHIEUYEUCAU_ID.ToString();
                txtNGAYYEUCAU.Text = String.Format("{0:dd/MM/yyyy}", phieuyeucau.NGAY_YEU_CAU.Value); 
				LoadCHITIETPHIEUYEUCAU(phieuyeucau);
			}
		}

		private void LoadCHITIETPHIEUYEUCAU(PHIEUYEUCAU phieuyeucau)
		{
			var lst = CHITIETPHIEUYEUCAURepository.SelectByPHIEUYEUCAU_ID(phieuyeucau.PHIEUYEUCAU_ID);
			if (lst.Count > 0)
			{
				foreach (var item in lst)
				{
					DataSource.Rows.Add(item.THIET_BI_ID, item.THIETBI.TEN_THIET_BI, item.SO_LUONG);
				}
			}
		}

	}

}
